import { fileURLToPath, URL } from 'node:url'
import WindiCSS from 'vite-plugin-windicss'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'

const env = loadEnv('', process.cwd())
// console.log('Loaded env:', env) // 启动前 输出所有环境变量
export default defineConfig({
  // base: '/my-app/', // 部署到服务器的子路径，不设置 默认是 /
  plugins: [
    vue(),
    WindiCSS(),
    vueDevTools(),
    AutoImport({
      imports: ['vue', 'vue-router', 'pinia'],
      dts: './src/auto-imports.d.ts',
      resolvers: [
        ElementPlusResolver(),
        IconsResolver({
          prefix: 'Icon',
        }),
      ],
    }),
    Components({
      resolvers: [
        ElementPlusResolver(),
        IconsResolver({
          enabledCollections: ['ep'],
        }),
      ],
    }),
    Icons({ autoInstall: true }),
  ],
  css: {
    preprocessorOptions: {
      // 添加了as *来全局导入variables.scss中的变量
      scss: {
        additionalData: `@use "@/styles/variables.scss" as *;`,
      },
    },
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  // 配置代理
  server: {
    proxy: {
      // '/api': {
      [env.VITE_BASE_API]: {
        target: env.VITE_SERVER_URL, //  import.meta.env报错
        changeOrigin: true,
        // rewrite: (path) => path.replace(/^\/api/, ''),
        // rewrite: (path) => path.replace(new RegExp(`^${env.VITE_BASE_API}`), ''),
      },
    },
  },
})
